<script setup>
  import { ref, computed } from "vue";

  // 当前选定的页码
  const currentPage = ref(1);

  // 总页数
  const totalPages = 20;

  // 每次显示的页码数量
  const visiblePagesCount = 5;

  // 当前页码范围的起始位置
  const pageStart = ref(1);

  // 动态计算当前显示的页码范围
  const visiblePages = computed(() => {
    const start = pageStart.value;
    const end = Math.min(totalPages, start + visiblePagesCount - 1);
    return Array.from({ length: end - start + 1 }, (_, i) => start + i);
  });

  // 点击具体页码
  const setPage = (page) => {
    if (page > 0 && page <= totalPages) {
      currentPage.value = page;
      document.activeElement.blur(); // 取消选中状态
    }
  };

  // 切换到上一页显示范围
  const previousPageDisplay = () => {
    if (pageStart.value > 1) {
      pageStart.value -= visiblePagesCount;
      pageStart.value = Math.max(1, pageStart.value); // 防止越界
      document.activeElement.blur(); // 取消选中状态
    }
  };

  // 切换到下一页显示范围
  const nextPageDisplay = () => {
    if (pageStart.value + visiblePagesCount - 1 < totalPages) {
      pageStart.value += visiblePagesCount;
      pageStart.value = Math.min(
        pageStart.value,
        totalPages - visiblePagesCount + 1
      ); // 防止越界
      document.activeElement.blur(); // 取消选中状态
    }
  };
</script>

<template>
  <div>
    <ul
      class="uk-pagination my-5 uk-flex-center"
      uk-margin
    >
      <!-- 上一页显示范围按钮 -->
      <li :class="{ 'uk-disabled': pageStart === 1 }">
        <a @click="previousPageDisplay">
          <span uk-pagination-previous></span>
        </a>
      </li>

      <!-- 动态页码按钮 -->
      <li
        v-for="page in visiblePages"
        :key="page"
        :class="{ 'uk-active': currentPage === page }"
      >
        <a @click="setPage(page)">
          <span>{{ page }}</span>
        </a>
      </li>

      <!-- 下一页显示范围按钮 -->
      <li
        :class="{
          'uk-disabled': pageStart + visiblePagesCount - 1 >= totalPages,
        }"
      >
        <a @click="nextPageDisplay">
          <span uk-pagination-next></span>
        </a>
      </li>
    </ul>
  </div>
</template>

<style scoped>
  /* 禁止文本选中 */
  .uk-pagination a {
    user-select: none;
  }

  /* 防止焦点效果 */
  .uk-pagination a:focus {
    outline: none;
  }
</style>
